package com.abc.proxy.cglib;

import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory implements MethodInterceptor {

   private Object target;

   public ProxyFactory(Object target){
      this.target = target;
   }

   public Object getInstance(){
      System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "/Users/czy/Documents");
      // 通过CGLIB动态代理获取代理对象的过程
      Enhancer en = new Enhancer();
      //设置代理类
      en.setSuperclass(target.getClass());
      //设置回调对象
      en.setCallback(this);
      //创建代理类
      return en.create();
   }


   @Override
   public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
      System.out.println("开启事务");

      Object obj = method.invoke(target,objects);

      System.out.println("关闭事务");

      return obj;
   }

}
